package upload

import (
	"context"
	"ginblog/tools/errDeal"
	"ginblog/utils"
	"ginblog/utils/errmsg"
	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"
	"mime/multipart"
)

var AccessKey = utils.AccessKey
var SecretKey = utils.SecretKey
var Bucket = utils.Bucket
var ImgUrl = utils.QiniuServer

type Upload struct {
	File     multipart.File
	FileSize int64
	errDeal.ErrDealWith
}

func (upload *Upload) UploadFile() (bool, string) {
	putPolicy := storage.PutPolicy{
		Scope: Bucket,
	}
	mac := qbox.NewMac(AccessKey, SecretKey)
	upToken := putPolicy.UploadToken(mac)
	conf := storage.Config{
		Zone:          &storage.ZoneHuadong,
		UseCdnDomains: false,
		UseHTTPS:      false,
	}

	putExtra := storage.PutExtra{}

	formUploader := storage.NewFormUploader(&conf)
	ret := storage.PutRet{}
	err := formUploader.PutWithoutKey(context.Background(), &ret, upToken, upload.File, upload.FileSize, &putExtra)
	if err != nil {
		upload.SteCodeMsg(errmsg.UPLOAD_FAIL)
		return false, ""
	}
	return true, ImgUrl + ret.Key
}
